package com.kvest.scanrecognizer.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.kvest.scanrecognizer.R;
import com.kvest.scanrecognizer.ui.fragment.MainFragment;
import com.kvest.scanrecognizer.utility.*;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: Kvest
 * Date: 07.09.13
 * Time: 15:07
 * To change this template use File | Settings | File Templates.
 */
public class MainActivity extends BaseActivity implements MainFragment.OnButtonsClickListener {
    private static final int IMAGE_CAPTURE_CODE = 0;
    private static final int SELECT_PICTURE_CODE = 1;

    private static final String JPEG_FILE_PREFIX = "IMG_";
    private static final String JPEG_FILE_SUFFIX = ".jpg";

    private static final String CURRENT_PHOTO_PATH_BUNDLE = "com.kvest.scanrecognizer.ui.activity.MainActivity.CURRENT_PHOTO_PATH";

    private String currentPhotoPath;
    private AlbumStorageDirFactory albumStorageDirFactory = null;

    @Override
    public void onCreate(Bundle savedState) {
        super.onCreate(savedState);
        setContentView(R.layout.fragment_container);

        if (savedState == null) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            try {
                transaction.add(R.id.container, new MainFragment());
            } finally {
                transaction.commit();
            }
        } else {
            currentPhotoPath = savedState.containsKey(CURRENT_PHOTO_PATH_BUNDLE) ?
                               savedState.getString(CURRENT_PHOTO_PATH_BUNDLE) : null;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
            albumStorageDirFactory = new FroyoAlbumDirFactory();
        } else {
            albumStorageDirFactory = new BaseAlbumDirFactory();
        }
    }

    @Override
    protected void onSaveInstanceState (Bundle outState) {
        super.onSaveInstanceState(outState);

        if (currentPhotoPath != null) {
            outState.putString(CURRENT_PHOTO_PATH_BUNDLE, currentPhotoPath);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (resultCode == RESULT_OK) {
            if (requestCode == IMAGE_CAPTURE_CODE) {
                if (currentPhotoPath != null) {
                    showPreview(currentPhotoPath);
                    currentPhotoPath = null;
                }
            }else if (requestCode == SELECT_PICTURE_CODE) {
                Uri selectedImageUri = intent.getData();
                String selectedImagePath = Utils.getImagePathByUri(this, selectedImageUri);
                showPreview(selectedImagePath);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu
        getMenuInflater().inflate(R.menu.main_menu, menu);

//        // Find the share item
//        MenuItem shareItem = menu.findItem(R.id.menu_share);
//
//        // Need to use MenuItemCompat to retrieve the Action Provider
//        shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
//        shareActionProvider.setShareIntent(getDefaultIntent());

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_settings) {
            startActivity(new Intent(MainActivity.this, SettingsActivity.class));
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void showPreview(String selectedImagePath) {
        Intent intent = new Intent(this, PreviewActivity.class);
        intent.putExtra(PreviewActivity.FILE_PATH_EXTRA, selectedImagePath);
        startActivity(intent);
    }

    @Override
    public void onTakePictureButtonClick() {
        dispatchTakePictureIntent(IMAGE_CAPTURE_CODE);
    }

    @Override
    public void onSelectPictureButtonClick() {
        dispatchSelectPictureIntent(SELECT_PICTURE_CODE);
    }

    @Override
    public void onManagerButtonClick() {
        startActivity(new Intent(this, ManagerActivity.class));
    }

    private void dispatchSelectPictureIntent(int actionCode) {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, actionCode);
    }

    private void dispatchTakePictureIntent(int actionCode) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File f = null;
        try {
            f = setUpPhotoFile();
            currentPhotoPath = f.getAbsolutePath();
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        } catch (IOException e) {
            e.printStackTrace();
            f = null;
            currentPhotoPath = null;
        }
        startActivityForResult(takePictureIntent, actionCode);
    }

    private String getAlbumName() {
        return getString(R.string.app_name);
    }

    private File getAlbumDir() {
        File storageDir = null;

        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            storageDir = albumStorageDirFactory.getAlbumStorageDir(getAlbumName());
            if (storageDir != null) {
                if (! storageDir.mkdirs()) {
                    if (! storageDir.exists()){
                        Log.d(getString(R.string.app_name), "failed to create directory");
                        return null;
                    }
                }
            }
        } else {
            Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
        }

        return storageDir;
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
        File albumF = getAlbumDir();
        File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
        return imageF;
    }

    private File setUpPhotoFile() throws IOException {
        File f = createImageFile();
        currentPhotoPath = f.getAbsolutePath();
        return f;
    }
}
